package com.nyj.sqlSession;

import com.nyj.pojo.Configuration;
import com.nyj.pojo.MappedStatement;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @author niuyj
 * @date 2020/4/30 23:17
 * @description 数据库CURD操作的实现类
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    //创建处理器对象
    private Executor simpleExecutor = new SimpleExecutor();

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {

        //获取key：statementId对应的value:MappedStatement
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<E> query = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            T o = (T) objects.get(0);
            return o;
        } else {
            throw new RuntimeException("结果为空或返回值过多");
        }
    }

    @Override
    public int add(String statementId, Object... params) throws NoSuchFieldException, IllegalAccessException, SQLException {
        //获取key：statementId对应的value:MappedStatement
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int i = simpleExecutor.doUpdate(configuration, mappedStatement, params);
        return i;
    }

    @Override
    public int update(String statementId, Object... params) throws NoSuchFieldException, IllegalAccessException, SQLException {
        //获取key：statementId对应的value:MappedStatement
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int i = simpleExecutor.doUpdate(configuration, mappedStatement, params);
        return i;
    }

    @Override
    public int delete(String statementId, Object... params) throws NoSuchFieldException, IllegalAccessException, SQLException {
        //获取key：statementId对应的value:MappedStatement
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int i = simpleExecutor.doUpdate(configuration, mappedStatement, params);
        return i;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // 使用JDK动态代理模式为Dao接口生成代理对象，并返回
        //代理对象调用接口中的任意方法，都会执行invoke方法
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            //invoke方法参数说明proxy:当前代理对象的引用，method：当前被调用方法的引用，args：传递的参数
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层最终执行的还是jdbc，根据不同情况，来选择调用哪个方法
                //准备参数1：statementId，sql语句的唯一标识，namespace.id，直接获取不到配置文件中的，规范：namespace：接口全限定名，id：接口方法名-》接口全限定名.接口方法名
                //方法名，findAll
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                //准备参数2：params，传入的参数，args
                //获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                /*//判断是否进行了泛型类型参数化
                if (genericReturnType instanceof ParameterizedType) {
                    return selectList(statementId, args);
                }*/
                /*此处需要优化，要判断是执行哪个方法,暂时先这么写*/
                switch (methodName){
                    case  "selectList":
                        return selectList(statementId, args);
                    case "selectOne":
                        return selectOne(statementId, args);
                    case "add":
                        return add(statementId, args);
                    case "update":
                        return update(statementId, args);
                    case "delete":
                        return delete(statementId, args);
                }

                return selectOne(statementId, args);
            }
        });
        return (T) proxyInstance;
    }
}
